//****************************************************************
//* Copyright (c) 2004 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   FullEconomicsSecurityProvider.java  $$
//* $$Revision:   1.2  $$
//* $$Author:   aponte  $$
//* $$Date:   Dec 15 2008 07:08:30  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ar.com.ford.it.fullEconomics.logic.PlantLogic;
import ar.com.ford.it.fullEconomics.logic.WSLSecurityLogic;
import ar.com.ford.it.fullEconomics.persistence.dto.Tms0005AccprofVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Tms0008UsrprofVw;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.security.ISecurityProvider;
import ar.com.ford.it.webengine.wslx.WslxUser;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class FullEconomicsSecurityProvider implements ISecurityProvider {
	
	private static final String CLASS_NAME = FullEconomicsSecurityProvider.class.getName();

	private static final ILogger log = LogFactory.getInstance().getLogger(
			CLASS_NAME);


    /**
     * Returns a list of the profiles associated with the user
     * 
     * @param   appName         application name
     * @param   wsluser         wsl user
     * @return  List<String>    profiles 
     */
	public List buildProfiles(String appName, WslxUser wslxuser) {
		
		String METHOD_NAME = "buildProfiles";
		
		String plantCode = null;
        boolean bPlantError = false;
        
        //Casteo el usuario, para luego guardar el codigo de planta correspondiente
        FullEconomicsWslxUser usuario = (FullEconomicsWslxUser)wslxuser;
        
        usuario.setName(wslxuser.getId());
        
        //Listado de retorno de perfiles
        ArrayList<String> ar = new ArrayList<String>();
        
        //Obtengo los perfiles del usuario a partir de su cdsid y systema asociado.
        WSLSecurityLogic wslLogic = new WSLSecurityLogic();
        Collection<Tms0008UsrprofVw> tmsUsrCollection = wslLogic.findUsr(usuario.getId(),appName);
        
        for (Tms0008UsrprofVw tms0005AccprofVw: tmsUsrCollection){
            System.out.println("*** "+tms0005AccprofVw.getMs0008ProfileCodeC()+" ***");
            ar.add(tms0005AccprofVw.getMs0008ProfileCodeC());
            
            //Si ya cargue una planta, y no hubo error
            if (plantCode != null && !bPlantError){
                //Verifico que sea igual a la anterior
                bPlantError = (!tms0005AccprofVw.getMs0008PlantCodeC().equals(plantCode));
            }else{
                plantCode = tms0005AccprofVw.getMs0008PlantCodeC();
            }
        }
        
        if (bPlantError){
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,"ERROR: El usuario tiene mas de una planta diferente asociada.");
        }else{
            //Obtengo la planta y la asocio con el usuario
            PlantLogic plantLogic = new PlantLogic();
            try {
				usuario.setTeesg01Plant(plantLogic.getPlant(plantCode));
			} catch (PersistenceException e) {
				log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
		                    "Build profile Exception", e);
			}
        }
        
        if (ar.size() == 0){
        	log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,"ERROR: El usuario no tiene perfiles asociados.");
        }
        
        return ar;
	}

	/**
     * Returns a list of tasks for an specific profile
     * 
     * @param   appName         application name
     * @param   wsluser         wsl user      
	 * @return  List<String>    tasks
	 */
	public List buildPermissions(String appName, WslxUser wslxuser) {
		
		String METHOD_NAME = "buildPermissions";
        
	    //Casteo el usuario, para luego obtener el codigo de planta correspondiente
        FullEconomicsWslxUser usuario = (FullEconomicsWslxUser)wslxuser;
        
        //Listado de retorno de tasks
        Set<String> tasksSet = new HashSet<String>();
        ArrayList<String> ar = new ArrayList<String>();
        
        //Obtengo un listado de tasks para los profiles asociados al usuario
        WSLSecurityLogic wslLogic = new WSLSecurityLogic();
        
        for (Object profile: usuario.getProfiles()){
            
            Collection<Tms0005AccprofVw> accProfList = wslLogic.findPermissonsByUsr(usuario.getTeesg01Plant().getEesg01PlantCodeC(), (String)profile, appName);
            
            for (Tms0005AccprofVw tms0005AccprofVw: accProfList){
                if (tasksSet.contains(tms0005AccprofVw.getMs0005TaskIdD())){
                    log.logp(Level.INFO, CLASS_NAME, METHOD_NAME,"El usuario ya tenia asociado el permiso a: "+tms0005AccprofVw.getMs0005TaskIdD());
                }else{
                	tasksSet.add(tms0005AccprofVw.getMs0005TaskIdD());
                }
            }
            
        }
        
        //Lo agrego a un listado de strings para el retorno
        ar.addAll(tasksSet);
        
        return ar;
	}

	/**
     * Lists the permissions for the menu
     * 
     * @param   appName         application name
     * @param   wsluser         wsl user      
     * @return  List<String>    menu permissions
	 */
	public List buildmenuAccess(String appName, WslxUser wslxuser) {
		return wslxuser.getPermissions();
	}

}
